package com.woyao;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.woyao.core.model.BaseResponse;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.DateUtil;
import com.woyao.core.util.ServiceFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

public class WelcomeActivity extends Activity {
    private static final String FILE_PATH = Environment.getExternalStorageDirectory() +"/" + "AutoUpdate" +"/";
    // 下载应用存放全路径
    private static final String FILE_NAME = FILE_PATH  + "woyaoooo"  + DateUtil.format(new Date(), "yyMMddHHmmss" ) + ".apk";

    private String apk_path = "http://www.woyaooo.com/static/upload/woyaooo.apk";
    private Intent intent;
    private TextView versionName;
    FrameLayout mainArea ;

    ProgressDialog progressDialog;
    private  Integer INSTALL_CODE = 333;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }


        setContentView(R.layout.activity_welcome);
        intent = new Intent(this, Welcome2Activity.class);


        versionName = (TextView) findViewById(R.id.version_name);

        versionName.setText(getCurrentVersion());
        try {
            updateVersion();
        }catch (Exception e){
            handleNext();
        }

    }


    private  void handleNext(){
        checkHasLogged();
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                startActivity(intent);
                finish();
            }
        }, 3000);
    }



    private void checkHasLogged() {
        //检查是否已经登陆过
        SharedPreferences shared = getSharedPreferences("login", MODE_PRIVATE);
        Boolean hasLogin = shared.getBoolean("logged", false);
        Integer userId = shared.getInt("userId", 0);
        String username = shared.getString("username", "");
        String displayname = shared.getString("displayname", "");
        String snailview = shared.getString("snailview", "");
//        String org = shared.getString("org", "");

        if (hasLogin && userId > 0) {
            WoyaoooApplication.userId = userId;
            WoyaoooApplication.username = username;
            WoyaoooApplication.displayname = displayname;
            WoyaoooApplication.snailview = snailview;
//            WoyaoooApplication.org = org;
            intent.setClass(this, ChanceActivity.class);
//            intent.putExtra("from","mydemand");
//            intent.setClass(this, DemandMediaActivity.class);
//            intent.setClass(WelcomeActivity.this, AddActivity.class);
//            intent.putExtra("id", 8247   );
        } else {
//            Intent intent = new Intent();
//            intent.setClass(this, LoginActivity.class);
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            startActivity(intent);
        }
    }


    private void updateVersion(){
        final String version =  "" + getCurrentVersion();

        AsyncTask<Void,Void,BaseResponse> loadTask =
                new AsyncTask<Void, Void, BaseResponse>() {
                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<BaseResponse> responseCall = svc.checkVersion(userId,version);
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                    @Override
                    protected void onPostExecute(final BaseResponse response) {

                        if(response != null && !response.isSuccess() ){
                            showNoticeDialog( response.getMessage(), response.getCondition() );

                        }else{
                            handleNext();
                        }

                    }
                };
        loadTask.execute((Void)null);
    }


    /**
     * 获取当前版本号
     */
    private String getCurrentVersion() {
        try {

            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);

            Log.e("woyaooo", "当前版本名和版本号" + info.versionName + "--" + info.versionCode);

            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();

            Log.e("woyaooo", "获取当前版本号出错");
            return "";
        }
    }

    /**
     * 显示提示更新对话框
     */
    private void showNoticeDialog(String update_describe, String downloadlink ) {
        apk_path = downloadlink;
        new AlertDialog.Builder(this)
                .setTitle("检测到新版本！")
                .setMessage(update_describe)
                .setPositiveButton("下载", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        showDownloadDialog();
                    }
                }).setNegativeButton("下次再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                handleNext();
            }
        }).create().show();
    }

    /**
     * 显示下载进度对话框
     */
    public void showDownloadDialog() {

        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("正在下载...");
        progressDialog.setCanceledOnTouchOutside(true);
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        new downloadAsyncTask().execute();
    }

    /**
     * 下载新版本应用
     */
    private class downloadAsyncTask extends AsyncTask<Void, Integer, Integer> {

        @Override
        protected void onPreExecute() {

            progressDialog.show();
        }

        @Override
        protected Integer doInBackground(Void... params) {


            URL url;
            HttpURLConnection connection = null;
            InputStream in = null;
            FileOutputStream out = null;
            try {
                url = new URL(apk_path);
                connection = (HttpURLConnection) url.openConnection();

                in = connection.getInputStream();
                long fileLength = connection.getContentLength();
                File file_path = new File(FILE_PATH);
                if (!file_path.exists()) {
                    file_path.mkdir();
                }

                out = new FileOutputStream(new File(FILE_NAME));//为指定的文件路径创建文件输出流
                byte[] buffer = new byte[1024 * 1024];
                int len = 0;
                long readLength = 0;


                while ((len = in.read(buffer)) != -1) {

                    out.write(buffer, 0, len);//从buffer的第0位开始读取len长度的字节到输出流
                    readLength += len;

                    int curProgress = (int) (((float) readLength / fileLength) * 100);


                    publishProgress(curProgress);

                    if (readLength >= fileLength) {

                        break;
                    }
                }

                out.flush();
                return 1;

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (connection != null) {
                    connection.disconnect();
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {

            progressDialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Integer integer) {

            progressDialog.dismiss();//关闭进度条
            //安装应用
            installApp();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == INSTALL_CODE){

            Log.e("woyaooo", "installed");
            handleNext();
        }
    }

    /**
     * 安装新版本应用
     */
    private void installApp() {
        File appFile = new File(FILE_NAME);
        if (!appFile.exists()) {
            return;
        }
        // 跳转到新版本应用安装页面
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://" + appFile.toString()), "application/vnd.android.package-archive");
        startActivityForResult(intent, INSTALL_CODE);
    }
}
